package com.itheima.cookiedemo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "cookieServlet",urlPatterns = "/cookieservlet")
public class CookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置中文输入
        response.setContentType("com.itheima.text/html;charset=UTF-8");

        //输出信息
        PrintWriter pw = response.getWriter();
        pw.write("欢迎访问本网站，您的最后访问时间为:<br>");


        //设置cookie信息
        Cookie cookie = new Cookie("time",System.currentTimeMillis()+"");

        //设置cookie最大存活时间
        cookie.setMaxAge(3600);

        //添加cookie到浏览器
        response.addCookie(cookie);


        //获取cookie打印信息
        Cookie[] cookies = request.getCookies();

        for (Cookie c : cookies) {
            if (c.getName().equals("time")) {
                SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

                String str = sim.format(new Date(Long.parseLong(c.getValue())));
                pw.write(str);
            }
        }


    }
}
